package demo;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class RenameTsToCj {

    public static void main(String[] args) throws IOException {
    	// 指定目录路径
        Path directory = Paths.get("E:\\code\\xls-web\\socket.d-dev\\javascript\\socketd\\src");

        try (Stream<Path> paths = Files.walk(directory)) {
            // 筛选出所有的 .ts 文件
            paths.filter(Files::isRegularFile)
                 .filter(path -> path.toString().toLowerCase().endsWith(".ts"))
                 .forEach(path -> {
                     String fileName = path.getFileName().toString();
                     // 使用正则表达式将驼峰风格转换为下划线风格
                     String newFileName = fileName.replaceFirst("\\.ts$", ""); // 移除 .ts 扩展名
                     Matcher matcher = Pattern.compile("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])").matcher(newFileName);
                     newFileName = matcher.replaceAll("_").toLowerCase(); // 将驼峰风格转换为下划线风格并转换为小写
                     // 确保文件名不以下划线开头
                     if (newFileName.startsWith("_")) {
                         newFileName = newFileName.substring(1);
                     }
                     newFileName += ".cj"; // 添加新的扩展名 .cj

                     // 创建新的路径
                     Path newPath = path.getParent().resolve(newFileName);
                     // 重命名文件
                     try {
                         Files.move(path, newPath, StandardCopyOption.REPLACE_EXISTING);
                     } catch (IOException e) {
                         System.err.println("Failed to rename " + fileName + ": " + e.getMessage());
                     }
                 });
        } catch (IOException e) {
            System.err.println("Failed to read directory: " + e.getMessage());
        }
    }

    private static void renameTsFile(Path tsPath) throws IOException {
        String fileName = tsPath.getFileName().toString();
        String newName = fileName.substring(0, fileName.length() - 3).toLowerCase()
                .replaceAll("([A-Z])", "_$1")
                .replaceFirst("^_", "")
                .replace(".", "_")
                .concat(".cj");

        Path newPath = tsPath.resolveSibling(newName);
        Files.move(tsPath, newPath, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Renamed " + tsPath + " to " + newPath);
    }
}
